//
//  WBComposeViewController.swift
//  仿写微博
//
//  Created by Apple on 17/8/10.
//  Copyright © 2017年 tuimao. All rights reserved.
//

import UIKit
import SVProgressHUD
class WBComposeViewController: UIViewController {
    ///发送按钮
    @IBOutlet var sendButton: UIButton!
    ///titleView
    @IBOutlet var titleLabel: UILabel!
    /// 文本编辑视图
    @IBOutlet weak var textView: WBComposeTextView!
    /// 底部工具栏
    @IBOutlet weak var toolbar: UIToolbar!
    /// 工具栏底部约束
    @IBOutlet weak var toolbarBottomCorn: NSLayoutConstraint!
    
    /// 表情输入视图
    lazy var emoticonView: CZEmoticonInputView = CZEmoticonInputView.inputView {[weak self] (emoticon) in
        
         self?.textView.insertEmoticon(em: emoticon)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        /// 监听键盘通知
        NotificationCenter.default.addObserver(self, selector: #selector(changeKeyBoard), name: Notification.Name.UIKeyboardWillChangeFrame, object: nil)
        
    }
    /// 视图开始弹出键盘
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        textView.becomeFirstResponder()
    }
    
    /// 视图消失收起键盘
    override func viewWillDisappear(_ animated: Bool) {
        
        super.viewWillDisappear(animated)
        textView.resignFirstResponder()
    }
    
    
    ///键盘改变的通知
    @objc fileprivate func changeKeyBoard(n:Notification){
        //键盘的缩进高度和相应动画时间
        guard let heightRect = (n.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue,
              let duration = (n.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue
        else{
            return
        }
        //缩进高度
        let offset = view.bounds.height - heightRect.origin.y
        /// toolbar的约束
        toolbarBottomCorn.constant = offset
        /// 添加动画
        UIView.animate(withDuration: duration) { 
            
            self.view.layoutIfNeeded()
        }
    }
    
    //关闭按钮
    @objc fileprivate func close(){
        dismiss(animated: true, completion: nil)
    }
    ///发布微博
    @IBAction func postStatus() {
        //guard let text = textView.text else {
           // return
        //}
        SVProgressHUD.setDefaultStyle(.dark)
        SVProgressHUD.showInfo(withStatus: "发送成功")
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) { 
            SVProgressHUD.setDefaultStyle(.light)
            self.close()
        }
        
        //WBNetworkManager.shared.postStatus(text: text) { (json, issuccess) in
           // self.close()
        //}
    }
    /// 注销通知
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    // 键盘按钮的点击方法
    @objc fileprivate func emoticonKeyboard(){
        //系统键盘textView.inputView = nil
        /// 1.准备测试键盘视图
//        let keyBoardView = UIView()
//        keyBoardView.backgroundColor = UIColor.blue
//        keyBoardView.frame = CGRect(x: 0, y: 0, width: 100, height: 253)
        //设置键盘
        textView.inputView = (textView.inputView == nil) ? emoticonView : nil
        //刷新键盘
        textView.reloadInputViews()
    }
}

///textView的代理
extension WBComposeViewController:UITextViewDelegate{
    func textViewDidChange(_ textView: UITextView) {
     sendButton.isEnabled = textView.hasText
    }
}


//MARK:  设置UI
fileprivate extension WBComposeViewController{
    //设置UI
    func setupUI() {
        view.backgroundColor = UIColor.white
        /// 设置nav
        setupNavigationBar()
        /// 设置toolbar
        setupToolbar()
    }
    /// 设置NAV
    func setupNavigationBar()  {
        //设置左右NavBar按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", fontsize: 14, target: self, action: #selector(close), isback: false)
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        //初始按钮状态
        sendButton.isEnabled = false
        //设置标题视图
        navigationItem.titleView = titleLabel
    }
    /// 设置底部工具栏
    func setupToolbar(){
        let itemSettings = [["imageName": "compose_toolbar_picture"],
                            ["imageName": "compose_mentionbutton_background"],
                            ["imageName": "compose_trendbutton_background"],
                            ["imageName": "compose_emoticonbutton_background", "actionName": "emoticonKeyboard"],
                            ["imageName": "compose_add_background"]]
        // 遍历数组
        var items = [UIBarButtonItem]()
        for s in itemSettings {
            
            guard let imageName = s["imageName"] else {
                continue
            }
            let image = UIImage(named: imageName)
            let imageHL = UIImage(named: imageName + "_highlighted")
            
            let btn = UIButton()
            
            btn.setImage(image, for: [])
            btn.setImage(imageHL, for: .highlighted)
            btn.sizeToFit()
            if let actionName = s["actionName"]{
                //添加点击事件
                btn.addTarget(self, action: Selector(actionName), for: .touchUpInside)
            }
            
            // 追加按钮
            items.append(UIBarButtonItem(customView: btn))
            
            // 追加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
            
        }
        // 删除末尾弹簧
        items.removeLast()
        
        toolbar.items = items
    }
    
    
    
    
    
}
